﻿using System;
using System.IO;
using Windows.ApplicationModel.DataTransfer;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace GifAnimator
{
    public class ImageFrame
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        //private BitmapImage image = null;
        //public BitmapImage Image
        //{
        //    get
        //    {
        //        return this.image;
        //    }
        //    set
        //    {
        //        if (this.image != value)
        //        {
        //            this.image = value;
        //            this.OnPropertyChanged("Image");
        //        }
        //    }
        //}

        private WriteableBitmap image = null;
        public WriteableBitmap Image
        {
            get
            {
                return this.image;
            }
            set
            {
                if (this.image != value)
                {
                    this.image = value;
                    this.OnPropertyChanged("Image");
                }
            }
        }

        public ImageSource ImageSource { get; set; }
        public UInt16 Duration { get; set; }
        public StorageFile File { get; set; }

        public ImageFrame()
        {
        }
        public ImageFrame(StorageFile file, UInt16 duration = 10)
        {
            this.File = file;
            this.ImageSource = new BitmapImage(new Uri(file.Path));
            this.Duration = duration;
            SetImageBmp(file);
        }
        public ImageFrame(WriteableBitmap writableBitmap, UInt16 duration = 10)
        {
            this.Image = writableBitmap;
            this.Duration = duration;
        }

        private async void SetImageBmp(StorageFile file)
        {
            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                var bmpImage = new BitmapImage();
                bmpImage.SetSource(stream);

                stream.Seek(0);

                var image = new WriteableBitmap(bmpImage.PixelWidth, bmpImage.PixelHeight);
                image.SetSource(stream);
                Image = image;
            }
        }

    }
}
